package com.fjec.market.rabbitmq.consumer;

import com.fjec.common.protocol.FjecFruitsProto;
import com.fjec.market.service.IBizPhysicalOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
@Slf4j
public class PaymentReceiptConsumer {

    @Resource
    private IBizPhysicalOrderService bizPhysicalOrderService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "${fjec.paid.paymentreceipt.queue.name}",
                            durable = "${fjec.paid.paymentreceipt.queue.durable}"
                    ),
                    exchange = @Exchange(
                            value = "${fjec.paid.paymentreceipt.exchange.name}",
                            durable = "${fjec.paid.paymentreceipt.exchange.durable}",
                            type = "${fjec.paid.paymentreceipt.exchange.type}",
                            ignoreDeclarationExceptions = "${fjec.paid.paymentreceipt.exchange.ignoreDeclarationExceptions}"
                    ),
                    key = "${fjec.paid.paymentreceipt.router.key}"
            )
    )
    @RabbitHandler
    public void onPaymentReceipt(Message message, Channel channel, @Headers Map<String, Object> headers) throws Exception {
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            FjecFruitsProto.FjecFruitsMsg msg = FjecFruitsProto.FjecFruitsMsg.parseFrom(message.getBody());
            if (msg.hasPaymentReceipt()) {
                FjecFruitsProto.PaymentReceipt paymentReceipt = msg.getPaymentReceipt();
                Long orderId = paymentReceipt.getOrderId();
                Long paymentId = paymentReceipt.getPaymentId();
                Integer orderStatus = paymentReceipt.getResult();
                Integer orderType = paymentReceipt.getOrderType();
                bizPhysicalOrderService.setOrderStatus(orderId, orderStatus, paymentId, orderType);
                channel.basicAck(deliveryTag, true);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            channel.basicReject(deliveryTag, false);
        }
    }
}
